package ml.kupin.search.listener;

import ml.kupin.search.mapper.IndexItemMapper;
import ml.kupin.common.vo.IndexItem;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * 监听kupin-manager模块发送的商品添加、编辑、删除消息，并在接收到消息之后，
 * 将商品信息同步到索引库中
 * Created by 小柯(Allen Kerr) on 17.5.4 16:11.
 */
public class ItemUpdateMessageListener implements MessageListener {

    @Autowired
    private IndexItemMapper indexItemMapper;
    @Autowired
    private SolrServer solrServer;

    private Logger logger = LoggerFactory.getLogger(ItemUpdateMessageListener.class);

    @Override
    public void onMessage(Message message) {
        logger.info("ItemUpdateMessageListener 接收到消息。");
        //转型
        TextMessage textMessage = (TextMessage) message;
        try {
            //取商品id
            String text = textMessage.getText();
            Long id = Long.valueOf(text);
            logger.info("商品id：" + id);
            //稍微等待一下，因为kupin-manager-service的事务提交需要时间
            //若未提交就取查询商品，肯定是查不到，或者查到的是编辑前的信息
            Thread.sleep(1000);
            //根据商品id查询商品信息
            IndexItem indexItem = indexItemMapper.selectByPrimaryKey(id);
            //添加判断，是否找到对应商品
            if (indexItem == null) {
                logger.error("未在数据库中找到对应商品！");
                return;
            }
            //创建文档对象
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("id", id);
            doc.addField("item_title", indexItem.getTitle());
            doc.addField("item_sell_point", indexItem.getSell_point());
            doc.addField("item_price", indexItem.getPrice());
            doc.addField("item_image", indexItem.getImage());
            doc.addField("item_category_name", indexItem.getCategory_name());
            //将文档对象添加到索引库中
            solrServer.add(doc);
            //提交
            solrServer.commit();
            logger.info("索引库更新成功！");
        } catch (Exception e) {
            logger.info("索引库更新失败！");
            logger.error("异常信息：", e);
            e.printStackTrace();
        }
    }
}
